<?php
define("SEARCH_LIMIT",50);
require_once("classes/db_functions.php");
require_once("classes/functions.php");
require_once("as.funcs.php");
$db = new db_functions();

$page = getFromInput("page");
$page = $page>0?$page:1;
$start = ($page-1)*SEARCH_LIMIT;

// BEZ VIEW STATUS
$vs = get_ViewStatus();
$bVS = array();
foreach ($vs["id"] as $id){
	$_vs = getFromInput("vs_$id");
	if ($_vs>0) {
		$bVS[] = $id;
	}
}

// BEZ KAMPANJA
$bKampanja = getFromInput("bez_kampanja");

// BEZ ZAKAZANOG SASTANKA
$bSastanak = null;
$bSastanakOD = getFromInput("bez_sastanak_od");
$bSastanakDO = getFromInput("bez_sastanak_do");
if (preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$bSastanakOD) && preg_match('/^\d{1,2}\.\d{1,2}\.\d{2,4}$/',$bSastanakDO)) {
	$bSastanak = array(
		"od" => date2int($bSastanakOD),
		"do" => date2int($bSastanakDO)
	);
}


$ra = $_SERVER['REMOTE_ADDR'];
if(strlen($ra)){
	$tmp = explode(".",$ra,4);
	$last = trim($tmp[3]);
	if($last < 200){
		$local = intval($last)+100;
	}else{
		$local = $last;
	}
	//echo $local;
}

$mesid =getFromInput("grad_komitent");
$lopsid = getFromInput("lok_opstina_komitent");
$nasid = getFromInput("naselje_komitent");
$ulid = getFromInput("ulica_id_komitent");
$broj = getFromInput("broj_komitent");

$delid = getFromInput("delatnost");

if($mesid<1 && $lopsid<1 && $nasid<1 && $ulid<1 && $broj<1){
	echo "<h2 style=\"color:red\">Morate odabrati mesto, lokalnu opštinu, naselje ili ulicu.</h2>";
}else{
	
	
	if($nasid>0){
		$lid = $nasid;
		$ltip = 3;
	}else{
		if($lopsid>0){
			$lid = $lopsid;
			$ltip = 2;
		}else{
			$lid = $mesid;
			$ltip = 1;
		}
	}
	$lids = array();
	$st = "lokacija: <i>".$db->getOne("SELECT lok_naziv FROM lokacije WHERE lid=$lid LIMIT 1")."</i>";
	$q = "SELECT adresa_id FROM adrese WHERE (adresa_lid=$lid";
	//echo "$ltip $lid";
	if($lid>0){
		switch ($ltip){
			case 3:
				//$q .= " AND adresa_lid=$lid";
				break;
			case 2:
				$nas = $db->select1("SELECT lid FROM lokacije WHERE lok_tip=3 AND lok_parent=$lid");
				if ($nas !== false) {
					foreach ($nas as $nid){
						$lids[] = $nid[0];
					}
				}
				break;
			case 1:
				$lops = $db->select1("SELECT lid FROM lokacije WHERE lok_tip=2 AND lok_parent=$lid");
				if($lops !== false){
					foreach ($lops as $loid){
						$lids[] = $loid[0];
						$nas = $db->select1("SELECT lid FROM lokacije WHERE lok_tip=3 AND lok_parent=".$loid[0]);
						if ($nas !== false) {
							foreach ($nas as $nid){
								$lids[] = $nid[0];
							}
						}
					}
				}
				break;
		}
		
	}
	$q_adresa = "(adresa_lid=$lid";
	if (count($lids)) {
		$lids = array_unique($lids);
		foreach ($lids as $l){
			$q_adresa .= " OR adresa_lid=$l";
		}
	}
	$q .= ")";
	$q_adresa .= ")";
	if($ulid>0){
		$q_adresa .= " AND adresa_ul_id=$ulid";
		$st .= ", ulica: <i>".$db->getOne("SELECT ulica_ime FROM ulice WHERE ulica_id=$ulid LIMIT 1")."</i>";
	}
	if($broj>0){
		$q_adresa .= " AND adresa_broj LIKE '$broj%'";
		$st .= ", broj: <i>$broj</i>";
	}
	
	$adrese = array();
	$ids = array();
	$_ids = array();
	$ukupno=0;
	
	echo "<h1>$st</h1>";
	
	//-----------------------
	//		komitenti
	//-----------------------
	if($delid<0){
		$q_select = "SELECT DISTINCT komitent_id as komid, komitent_name, komitent_adresa, komitent_direktor, komitent_direktor_tel";
		$q_from = "FROM komitenti, adrese ";
		$q_where = " WHERE komitent_adresa=adresa_id ";
		
		$q_where .= " AND ($q_adresa)";
		
		
		if (count($bVS)) {
			$q_where .= " AND (1";
			foreach ($bVS as $v){
				$q_where .= " AND komitent_view_status!=$v";
			}
			$q_where .= ")";
		}
		
		if ($bKampanja>0) {
			$q_where .= " AND 0=(SELECT count(*) FROM komitenti_kampanje WHERE komitenti_kampanje.komitent_id=komid AND kampanja_id=$bKampanja)";
		}
		
		if ($bSastanak) {
			$q_where .= " AND 0=(SELECT count(*)"
					   ." FROM rokovnik r, rokovnik_result rr)"
					   ." WHERE r.id=rr.rokovnik_id"
					   ." AND rr.type=3"
					   ." AND r.komitent_id=komid"
					   ." AND rr.time>=".$bSastanak["od"]
					   ." AND rr.time<=".(intval($bSastanak["do"])+(60*60*24))
					   .")";
		}
		
		
		$ukupno += $db->getOne("SELECT count(komitent_id) $q_from $q_where");
		
		
		$q = "$q_select $q_from $q_where ORDER BY komitent_name LIMIT $start,".SEARCH_LIMIT;
		echo $q;
		die();
		$res = $db->select2($q);
		if($res[0]){
			foreach ($res as $kk=>$komitent){
				if(array_search($komitent["komitent_id"],$ids) === false){
					$ids[] = $komitent["komitent_id"];
				}
			}
		}
		//$ukupno += count($ids);
	}
	
	
	$q_where = "";
	//-----------------------
	// komitenti_delatnosti
	//-----------------------
	$q_select = "SELECT DISTINCT k.komitent_id, k.komitent_name, k.komitent_direktor, k.komitent_direktor_tel, kd.komdel_adresa_id as komitent_adresa ";
	$q_from = "FROM komitenti k, komitenti_delatnosti kd, adrese ";
	$q_where = "WHERE k.komitent_view_status != 4 "
			  ."AND k.komitent_id=kd.komdel_kom_id "
			  ."AND komdel_adresa_id=adresa_id ";
		if($delid>0){
			$q_where .= "AND komdel_del_id=$delid ";
			$st .= ", delatnost: <i>".$db->getOne("SELECT delatnost_ime FROM delatnosti WHERE delatnost_id=$delid LIMIT 1")."</i>";
		}
		
		$q_where .= " AND ($q_adresa)";
	
	// VIEW STATUS FILTER	
	if (count($bVS)>0){
		$q_where .= " AND (1";
		foreach ($bVS as $b){
			$q_where .= " AND k.komitent_view_status!=$b";
		}
		$q_where .= ")";
		/*$q = "SELECT 1 FROM komitenti WHERE komitent_id=".$del["komitent_id"]." AND (0";
		foreach ($bVS as $vsid){
			$q .= " OR komitent_view_status=$vsid";
		}
		$imavs = $db->getOne($q.")");
		if ($imavs) {
			$ok=false;
		}*/
	}	
	
	$ukupno_del = $db->getOne("SELECT count(*) $q_from $q_where");
	//echo "<br />$ukupno_del<br/>";
	
	$q = "$q_select $q_from $q_where ORDER BY komitent_name LIMIT $start,".SEARCH_LIMIT;
	//echo $q;
	$res_del = $db->select2($q);
	if($res_del[0]){
		
		foreach ($res_del as $k=>$del){
			$ok = true;
			
			if ($bKampanja>0){
				$imakampanju = $db->getOne("SELECT 1 FROM komitenti_kampanje WHERE kampanja_id=$bKampanja AND komitent_id=".$del["komitent_id"]);
				if ($imakampanju) {
					$ok=false;
				}
			}
			if ($bSastanak) {
				
				$q = "SELECT 1 FROM rokovnik r, rokovnik_result rr "
					."WHERE r.id=rr.rokovnik_id "
					."AND rr.type=3 "
					."AND r.komitent_id=".$del["komitent_id"]." "
					."AND rr.time>=".$bSastanak["od"]." "
					."AND rr.time<=".(intval($bSastanak["do"])+(60*60*24));
				
				$imasastanak = intval($db->getOne($q));
				if ($imasastanak>0) {
					$ok=false;
				}
			}
			if (!$ok) {
				unset($res_del[$k]);
				$ukupno_del--;
			}
		}
		if($res[0]){
			$all_res = array_merge($res,$res_del);
		}else{
			$all_res = $res_del;
		}
	}else{
		$all_res = $res;
	}
	$ukupno = $ukupno+$ukupno_del;
	
	
	$assign("search_term",$st);
	$ids = array();
	if($all_res){
		
		$num_pages = bcdiv($ukupno,SEARCH_LIMIT,0);
		if ($ukupno%SEARCH_LIMIT) {
			$num_pages++;
		}
		//echo "page: $page";
		for ($i=1; $i<=$num_pages; $i++){
			$pages[] = $i;
			if ($i==$page) {
				$pages_selected[] = ' id="current"';
			}else{
				$pages_selected[] = '';
			}
		}
		
		//$all_res = $sortRes($all_res);
		foreach ($all_res as $k=>$komitent){
			$num[] = (($page-1)*SEARCH_LIMIT)+$k+1;
			$adr = $adrese->getAll($komitent["komitent_adresa"]);
			$tels = $db->select2("SELECT DISTINCT telefon, fax FROM komitenti_telefoni WHERE kom_id=".$komitent["komitent_id"]);
			$emails = $db->select2("SELECT DISTINCT email FROM komitenti_emails WHERE kom_id=".$komitent["komitent_id"]);
			
			$zrs = $db->select2("SELECT DISTINCT ziro_value, banka_name FROM komitenti_ziro_racuni, banke WHERE komitenti_ziro_racuni.ziro_banka_id=banke.banka_id AND komitenti_ziro_racuni.ziro_komitent_id=".$komitent["komitent_id"]);
			//echo "SELECT DISTINCT ziro_value, banka_name FROM komitenti_ziro_racuni, banke WHERE komitenti_ziro_racuni.ziro_banka_id=banke.banka_id AND komitenti_ziro_racuni.ziro_komitent_id=".$komitent["komitent_id"]."<br />";
			
			$dels = $db->select2("SELECT DISTINCT delatnost_ime FROM komitenti_delatnosti kd, delatnosti d WHERE kd.komdel_del_id=d.delatnost_id AND kd.komdel_kom_id=".$komitent["komitent_id"]);
			
			
			$faxs = $telss = $mails = $zir = $delas = array();
			if($tels[0]){
				foreach ($tels as $tel){
					if($tel["fax"]){
						$faxs[] = $tel["telefon"];
					}else{
						$telss[] = '<a target="sophone" onclick="event.stopPropagation()" href="http://192.168.5.2/gw/call.php?l='.$local.'&r='.preg_replace('/[^\d]/',"",$tel["telefon"]).'">'.$tel["telefon"].'</a>';
					}
				}
			}
			//print_r($telss);
			if($emails[0]){
				foreach ($emails as $mail){
					$mails[] = $mail["email"];
				}
			}
			if($zrs[0]){
				foreach ($zrs as $zr){
					$zir[] = $zr["banka_name"].":<br />".$zr["ziro_value"];
				}
			}
			//echo ($komitent["komitent_id"])." ";
			//print_rarray($zir);
			
			if($dels[0]){
				foreach ($dels as $d){
					$delas[] = $d["delatnost_ime"];
				}
			}
			
			$ids[] = $komitent["komitent_id"];
			$names[] = $komitent["komitent_name"];
			$names_url[] = urlencode($komitent["komitent_name"]);
			$adrs[] = $adr["ulica"]." ".$adr["broj"]."<br />".$adr["lokacija"]["mesto"]["name"];
			$dirs[] = $komitent["komitent_direktor"];
			$telefon[] = @implode("<br />",$telss);
			$fax[] = @implode("<br />", $faxs);
			$email[] = @implode("<br />",$mails);
			$ziros[] = @implode("<br /><br />",$zir);
			$delatnost[] = @implode("<br />",$delas);
		}
		$assign("page",$pages);
		$assign("current_page",$pages_selected);
		$assign("info",$ukupno);
		$assign("num",$num);
		$assign("id",$ids);
		$assign("name",$names);
		$assign("name_url",$names_url);
		$assign("adresa",$adrs);
		$assign("direktor",$dirs);
		$assign("tel",$telefon);
		$assign("fax",$fax);
		$assign("email",$email);
		$assign("ziro",$ziros);
		$assign("del",$delatnost);
		
		echo $parseTemplate("komitenti/adv_search_table.tpl");
	}else{
		echo "No results ";
	}
}
?>